//
//  CreatePassWordViewCtrl.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/18.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "CreatePassWordViewCtrl.h"
#import "QBImagePickerController.h"
#import "CameraManager.h"
#import "ZYQAssetPickerController.h"
#import "VPImageCropperViewController.h"

@interface CreatePassWordViewCtrl () <LCActionSheetDelegate,UIImagePickerControllerDelegate,QBImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate,ZYQAssetPickerControllerDelegate> {
    NSData *logoimgData;
    
}

@property (weak, nonatomic) IBOutlet UIButton *addLogoBtn;

@property (weak, nonatomic) IBOutlet UITextField *nameTextfield;

@property (weak, nonatomic) IBOutlet UITextField *passWordField;

@property (weak, nonatomic) IBOutlet UITextField *confirmPwField;

@property (weak, nonatomic) IBOutlet UIButton *beginBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topCons;

- (IBAction)choseYourPortrait:(id)sender;

- (IBAction)beginYourJourney:(id)sender;

- (IBAction)goBack:(id)sender;

@end

@implementation CreatePassWordViewCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    //测试用代码
    self.nameTextfield.text = @"jack";
    self.passWordField.text = @"jack.songxuhua";
    self.confirmPwField.text = @"jack.songxuhua";
    setCornerRadius(self.beginBtn, 20.0f);
    [self addNotifications];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 通知
- (void)addNotifications {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
    
}

#pragma mark - 界面刷新
- (void)reloadLogoBtn:(UIImage *) editedImage{
    [self.addLogoBtn setBackgroundImage:editedImage forState:UIControlStateNormal];
    [self.addLogoBtn setTitle:@"" forState:UIControlStateNormal];
}

- (BOOL)isAllParamsVaild {
    if (![self isAllParamsisnoEmpty]) {
        return NO;
    }
    if (![self.passWordField.text isEqualToString:self.confirmPwField.text]) {
        [SVProgressHUD showErrorWithStatus:@"Password and confirmation password is different"];
        return NO;
    }
    return YES;
}

- (BOOL)isAllParamsisnoEmpty {
    if ([self isNameParamsEmpty] || [self isPwParamsEmpty] || [self isCoPwParamsEmpty]) {
        [SVProgressHUD showErrorWithStatus:@"The information is incomplete"];
        return NO;
    }
    return YES;
}

- (BOOL)isNameParamsEmpty {
    return self.nameTextfield.text.length <= 0;
}
- (BOOL)isPwParamsEmpty {
    return self.passWordField.text.length <= 0;
}
- (BOOL)isCoPwParamsEmpty {
    return self.confirmPwField.text.length <= 0;
}

#pragma mark delegate :IBActionSheetDelegate
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self presentCameraController];
    } else if (buttonIndex == 1) {
        [self presentImagePickerController];
    }
}

- (void)presentCameraController {
    WeakSelf(ws);
    [CameraManager authorizationStatusForCamera:^(BOOL granted) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *imgPicker=[[UIImagePickerController alloc] init];
            imgPicker.delegate= ws;
            imgPicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            [ws.navigationController presentViewController:imgPicker animated:YES completion:^{
                
            }];
        }
    }];
}

- (void)presentImagePickerController {
    ALAuthorizationStatus status = [CameraManager authorizationStatusForPhotoLibary];
    if (status == ALAuthorizationStatusAuthorized || status == ALAuthorizationStatusNotDetermined) {
        ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
        picker.maximumNumberOfSelection = 1;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate= self;
        picker.personDataController = self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
        [self presentViewController:picker animated:YES completion:NULL];
    }
}


#pragma mark - UIImagePickerControllerDelegate & QBImagePickerControllerDelegate

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {

    for (PHAsset *asset in assets) {
        BOOL original = YES;
        // 是否要原图
        CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        // 同步获得图片, 只会返回1张图片
        options.synchronous = YES;
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            NSLog(@"%@", result);
	        }];

//        NSLog(@"fileName is %@",asset.)
       // UIImage *image
        // Do something with the asset
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];

}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // info 包含了图片的数据
    UIImage *originalImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
 
    UIImage *compressImage = scaleImageToMaxSize(originalImage);
    [self reloadLogoBtn:compressImage];
    NSData *imageData = UIImageJPEGRepresentation(compressImage,1.0f);
    //暂存
    logoimgData = imageData;
    //图片上传和其他资料一起用form表单上传
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        //
        
    }];
}


#pragma mark VPImageCropperDelegate

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    
}


- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
    [self reloadLogoBtn:editedImage];
    NSData *data = UIImageJPEGRepresentation(editedImage, 1.0);
    logoimgData = data;
    //图片上传和其他资料一起用form表单上传
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    cropperViewController.navigationController.navigationBar.hidden = NO;
    [cropperViewController.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 通知事件
-(void)keyboardWillChangeFrame:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%@",NSStringFromCGRect(keyboardF));
    
    CGFloat keheight = keyboardF.size.height;
    CGFloat keyY = keyboardF.origin.y;
    
    if (self.beginBtn.bottom > keyY) {
        [UIView animateWithDuration:duration animations:^{
            self.topCons.constant = keyY - self.logoTopToSignBtnBot;
            [self.view layoutIfNeeded];
        }];
    }
    if (keyY >= kScreenHeight && self.topCons.constant != 120) {
        [UIView animateWithDuration:duration animations:^{
            self.topCons.constant = 120;
            [self.view layoutIfNeeded];
        }];
    }
}

-(void)keyboardDidChangeFrame:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    //    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%@",NSStringFromCGRect(keyboardF));
    
    
}

#pragma mark -action事件
- (IBAction)choseYourPortrait:(id)sender {
    [self.view endEditing:YES];
    LCActionSheet *actionSheet = [[LCActionSheet alloc] initWithTitle:nil buttonTitles:@[@"拍照",@"从相册选取"] redButtonIndex:0 delegate:self];
    [actionSheet show];
}


- (IBAction)beginYourJourney:(id)sender {
    if ([self isAllParamsVaild]) {//图片上传和其他资料一起用form表单上传
        NSString *name = self.nameTextfield.text;
        NSString *pw = self.passWordField.text;
        NSString *coPw = self.confirmPwField.text;
        //表单上传
        //先假设成功了,跳转
        [kUserDefaults setObject:pw forKey:LOGIN_PASSWord];

        [self dismissViewControllerAnimated:YES completion:^{
            [NSNotificationCenter postCreatePwNF:nil];
        }];
    }
}

- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - getter 
- (CGFloat)logoTopToSignBtnBot {
    return self.beginBtn.bottom - self.addLogoBtn.top;
}


@end
